package com.personnel.rbac.action;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.personnel.action.BaseAction;
import com.personnel.rbac.model.Department;
import com.personnel.rbac.model.EndUser;
import com.personnel.rbac.model.view.VDeptUser;
@Component("userAction")
@Scope("prototype")
public class UserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6447415593724534456L;
	private EndUser endUser=new EndUser();
	@Override
	public Object getModel() {
		// TODO Auto-generated method stub
		String deptId=request.getParameter("foreignKey");
		Department dept=new Department();
		dept.setDeptId(deptId);
		endUser.setDepartment(dept);
		return endUser;
	}
	/**
	 *用户表格的更新方法
	 */
	public void doUpdateList(){
		//[{sql:"update EndUser set name='zsp'"},{}]
		try{
			String[] updateSqls=jsonBuilder.jsonSqlToString(strData);
			pcServiceTemplate.executeBatchHql(updateSqls);
			String[] ids=jsonBuilder.jsonSqlToId(strData);
			for(String id:ids){
				EndUser user = (EndUser) pcServiceTemplate.findById(EndUser.class, id);
				VDeptUser vdu = (VDeptUser) pcServiceTemplate.findById(VDeptUser.class, id);
				updateView(user,vdu);
			}
			toWrite(jsonBuilder.returnSuccessJson("'"+updateSqls.length+"条记录被更新'"));
		}catch(Exception e){
			logger.error("批量更新失败，错误信息:"+e.getMessage());
			toWrite(jsonBuilder.returnFailureJson("'批量更新失败，错误信息："+e.getMessage()+"'"));
		}
	}
	/**
	 * 更新“视图表”
	 * @param user
	 * @param vdu
	 */
	public void updateView(EndUser user,VDeptUser vdu){
		if(vdu==null){
			StringBuffer sql = new StringBuffer("insert into vdeptuser ");
			sql.append("(id,text,code,nodeType,NodeInfo,nodeInfoType,parent,orderIndex,disabled,icon) ");
			sql.append("values('"+user.getUserId()+"',");
			sql.append("'"+user.getUsername()+"',");
			sql.append("'"+user.getUserCode()+"',");
			sql.append("'LEAF',");
			sql.append("'User',");
			sql.append("'',");
			sql.append("'"+user.getDepartment().getDeptId()+"',");
			sql.append("'0',");
			sql.append("'false',");
			sql.append("''");
			sql.append(")");
			pcServiceTemplate.executeSql(sql.toString());
		}else{
			StringBuffer sql = new StringBuffer("update vdeptuser v set ");
			sql.append("v.text ='"+user.getUsername()+"',");
			sql.append("v.code ='"+user.getUserCode()+"',");
			sql.append("v.nodeType ='LEAF',");
			sql.append("v.NodeInfo ='User',");
			sql.append("v.nodeInfoType ='',");
			sql.append("v.parent ='"+user.getDepartment().getDeptId()+"',");
			sql.append("v.orderIndex ='0',");
			sql.append("v.disabled ='false',");
			sql.append("v.icon ='' where v.id='"+vdu.getId()+"'");
			pcServiceTemplate.executeSql(sql.toString());
		}
	}
}
